//
//  UIView+MyOther.m
//  MoKaClient
//
//  Created by 叶影 on 2017/10/26.
//  Copyright © 2017年 胡小龙. All rights reserved.
//

#import "UIView+MyOther.h"
#import <objc/runtime.h>
#import <QuartzCore/QuartzCore.h>

static char kDTActionHandlerTapBlockKey;
static char kDTActionHandlerTapGestureKey;

@implementation UIView (MyOther)


- (UIViewController *)viewController {
    UIResponder *next = self.nextResponder;
    do {
        //判断响应者是否为视图控制器
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        next = next.nextResponder;
    } while (next != nil);
    return nil;
}

- (void)setTapActionWithBlock:(void (^)(UITapGestureRecognizer *gest))block {
    UITapGestureRecognizer *gesture = objc_getAssociatedObject(self,&kDTActionHandlerTapGestureKey);
    if (!gesture) {
        gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(__handleActionForTapGesture:)];
        [self addGestureRecognizer:gesture];
        objc_setAssociatedObject(self, &kDTActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    }
    objc_setAssociatedObject(self, &kDTActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
}

- (void)__handleActionForTapGesture:(UITapGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateRecognized) {
        void(^action)(UITapGestureRecognizer *gest) = objc_getAssociatedObject(self, &kDTActionHandlerTapBlockKey);
        if (action) {
            action(gesture);
        }
    }
}

- (void)removeAllSubViews {
    for (id objc in [self subviews]) {
        if ([objc isKindOfClass:[UIView class]]) {
            UIView *view = (UIView *)objc;
            [view removeFromSuperview];
        }
    }
}

- (void)removeSubviewsWithSubviewClass:(Class)cls {
    for (UIView *view in [self subviews]) {
        if ([view isKindOfClass:cls]) {
            [view removeFromSuperview];
        }
    }
}

- (void)removeSubviewsWithSubviewTag:(NSInteger)tag {
    UIView *view = [self viewWithTag:tag];
    [view removeFromSuperview];
}

- (void)makeBorderWithColor:(UIColor *)borderColor Width:(CGFloat)borderWidth {
    self.layer.masksToBounds = YES;
    self.layer.borderWidth = borderWidth;
    self.layer.borderColor = borderColor.CGColor;
}



@end
